﻿using Common;
using NationalInstruments.VisaNS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ResourceManager = NationalInstruments.VisaNS.ResourceManager;

namespace Device
{
    /// <summary>
    /// 示波器类
    /// </summary>
    public class DHO802
    {
        private static CVisaOpt m_VisaOpt;

        private static bool connected = false;

        private static string deviceName = "示波器DHO802";

        /// <summary>
        /// 串口连接
        /// </summary>
        public static void Connect()
        {
            if (connected) return;
            string m_strResourceName = null;
            m_VisaOpt = new CVisaOpt();
            string[] InstrResourceArray = m_VisaOpt.FindResource("?*INSTR"); //查找资源
            if (InstrResourceArray[0] == "未能找到可用资源")
            {
                Mylog.Debug($"{deviceName} [{InstrResourceArray[0]}]");
            }
            else
            {
                //选取DHO800系列仪器作为选中仪器
                for (int i = 0; i < InstrResourceArray.Length; i++)
                {
                    if (InstrResourceArray[i].Contains("DHO8"))
                    {
                        m_strResourceName = InstrResourceArray[i];
                    }
                }
            }
            //如果没有找到指定仪器直接退出
            if (m_strResourceName == null)
            {
                Mylog.Debug($" {deviceName} [{InstrResourceArray[0]}]");
                return;
            }
            m_VisaOpt.OpenResource(m_strResourceName);
            connected = true;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public static void init()
        {
            //自动测试
            SendCmd(":AUToset");
            //设置为正弦波
            SendCmd(":SOURce:FUNCtion SINusoid");
        }

        /// <summary>
        /// 读取幅值
        /// </summary>
        /// <returns> </returns>
        public static double GetAmplitude()
        {
            string cmd = ":MEASure:ITEM? VAMP";
            double result = double.Parse(SendCmdAndWaitReturn(cmd));
            return result;
        }

        /// <summary>
        /// 断开连接
        /// </summary>
        public static void Close()
        {
            m_VisaOpt.Release();
        }

        private static void SendCmd(string cmd)
        {
            Mylog.Debug($" {deviceName} [{cmd}]");
            m_VisaOpt.Write(cmd);
        }

        private static string SendCmdAndWaitReturn(string cmd)
        {
            SendCmd(cmd);
            string recvData = m_VisaOpt.Read();
            return recvData;
        }
    }
}